package admin

import (
	"chaowan/service"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
)

const (
	pturl = "https://api.gaoleilei.com/"
)

func UploadFile(c *gin.Context) {
	/*
	   通过form-data上传文件，文件名：file
	*/
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 0,
			"msg":     "失败",
			"data":    "on",
		})
		return
	}
	fileHandle, err1 := file.Open() //打开上传文件
	if err1 != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 0,
			"msg":     "失败",
			"data":    "on",
		})
		return
	}
	defer fileHandle.Close()
	fileByte, err2 := ioutil.ReadAll(fileHandle) //获取上传文件字节流
	if err2 != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 0,
			"msg":     "失败",
			"data":    "on",
		})
		return
	}
	url, err := service.Upload(file.Filename, fileByte)
	//unix_int := time.Now().Unix() // 时间戳，int类型
	//time_unix_str := strconv.FormatInt(unix_int, 10)
	//file_path := "upload/image/" + time_unix_str + file.Filename // 设置保存文件的路径，不要忘了后面的文件名
	//c.SaveUploadedFile(file, file_path)
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"msg":     "上传成功",
		"data":    url,
	})
	return
}
